package priv.bestbeat.reportcenter.core.pdf.image;

import com.itextpdf.io.image.ImageData;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.geom.*;
import com.itextpdf.kernel.geom.Vector;
import com.itextpdf.kernel.pdf.*;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.kernel.pdf.canvas.parser.PdfDocumentContentParser;
import priv.bestbeat.reportcenter.core.exception.ParseException;
import priv.bestbeat.reportcenter.core.pdf.TextObjEventListener;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.*;
import java.util.regex.Pattern;

/**
 * @author bestbeat
 * @date 2022/4/9
 */
public class ImageToTemplate {

    private static final Pattern PLACEHOLDER_REG = Pattern.compile("^\\$\\{replace-\\w+\\}$");

    /**
     *
     * @param imageMap key 在模板文件中不允许快捷复制只允许手动输入，原因是复制容易出现意想不到的错误解析
     * @param targetUrl
     * @param templateUrl
     * @throws IOException
     */
    public static void parseTemplate(Map<String,Image> imageMap,String targetUrl ,String templateUrl) throws IOException {

        PdfReader pdfReader = new PdfReader(templateUrl);
        PdfWriter pdfWriter = new PdfWriter(targetUrl);
        PdfDocument document = new PdfDocument(pdfReader,pdfWriter);

        PdfDocumentContentParser parser = new PdfDocumentContentParser(document);

        int pages = document.getNumberOfPages();


        for (int i = 1; i < pages + 1; i++) {
            TextObjEventListener eventListener = new TextObjEventListener();
            parser.processContent(i,eventListener);

            final ParseException ex = new ParseException();
            Map<String,List<Vector>> textObjMap = eventListener.getTextObjMap();
            int finalI = i;
            textObjMap.entrySet().stream().filter(entry -> PLACEHOLDER_REG.matcher(entry.getKey()).matches())
                    .anyMatch(entry -> {
                        Vector firstStart = entry.getValue().get(0);
                        Image image = imageMap.get(entry.getKey());
                        if (image == null) {
                            ex.initCause(new NullPointerException());
                            return true;
                        }
                        try {
                            ImageData imageData = ImageDataFactory.create(image.getUrl());

                            float x = firstStart.get(Vector.I1),y =firstStart.get(Vector.I2);
                            PdfPage page = document.getPage(finalI);
                            Rectangle pageSize = page.getPageSize();
                            float imageHeight = Math.min(pageSize.getHeight(),image.getHeight());
                            float imageWidth = Math.min(pageSize.getWidth(),image.getWidth());

                            PdfCanvas canvas = new PdfCanvas(page);
                            List<Point> points = new ArrayList<>(4);
                            points.add(new Point(x + image.getRepairX(),y + image.getRepairY()));
                            points.add(new Point(x + imageWidth ,y + image.getRepairY()));
                            points.add(new Point(x + imageWidth,y - imageHeight));
                            points.add(new Point(x + image.getRepairX(),y - imageHeight));

                            Rectangle rectangle = Rectangle.calculateBBox(points);
                            canvas.addImageFittedIntoRectangle(imageData,rectangle,false);
                            canvas.fillStroke();
                        } catch (MalformedURLException e) {
                            ex.initCause(e);
                            return true;
                        }

                        return false;
                    });

            if (ex.hasError()) {
                throw ex;
            }
        }

        pdfWriter.flush();
        document.close();
        pdfWriter.close();
        pdfReader.close();

    }

}
